import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../components/login.vue'
import Home from '../components/Home.vue'
import User from '../components/user/User.vue'
import Welcome from '../components/welcome.vue'
import Rights from '../components/power/rights.vue'
import Roles from '../components/power/roles.vue'

Vue.use(VueRouter)

const routes = [
    {path: '/',redirect: '/login'},  //如果访问的是'/'，就跳转到'/login'页面
  	{path: '/login',component: Login},
	{path: '/home',
	component: Home,
	redirect: '/welcome',
		children: [
			{path: '/welcome',component: Welcome},
			{path: '/users',component: User},
			{path: '/rights',component: Rights},
			{path: '/roles',component: Roles}
		]
	}
	
]

const router = new VueRouter({
  routes
})

// 添加导航守卫，如果请求中携带token就放行，如果没有就跳转到登录页面
router.beforeEach((to,from,next) =>{
	// to将要访问的url
	// from当前的url
	// next() 放行  next('/login')跳转到/login对应的组件
	// 登录的请求直接放行
	if(to.path === '/login') return next();
	// 获得请求中的token,有token放行，没有跳转到登录页面
	const token = window.sessionStorage.getItem('token')
	if(!token) return next('/login')
	// 有token直接放行
	next();
})

export default router
